package com.shuqi.service;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.List;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.IBinder;
import android.os.SystemClock;
import android.text.TextUtils;

import com.shuqi.activity.BookCoverActivity;
import com.shuqi.activity.WebCommonActivity;
import com.shuqi.application.ShuqiApplication;
import com.shuqi.common.CheckPushMessage;
import com.shuqi.common.CheckPushMessage.CheckPushMessageLinstener;
import com.shuqi.common.Config;
import com.shuqi.common.ConfigVersion;
import com.shuqi.common.FunctionsSwitch;
import com.shuqi.common.utils.Log4an;
import com.shuqi.controller.Loading;
import com.shuqi.controller.R;
import com.shuqi.model.bean.CheckBookUpdateInfo;
import com.shuqi.model.bean.CheckPushMessageInfo;
import com.shuqi.model.manager.MyAccountManager;
import com.shuqi.model.sharedprefs.SpConfig;
import com.shuqi.statistics.StatisticsEventID;
import com.shuqi.statistics.StatisticsUtils;

/**
 * 通知栏提醒服务 <br>
 * intent int 参数名:INTENT_NAME_ACTION <br>
 * INTENT_NAME_ACTION 对应的值：ACTION_*** 控制是否强制联网检查
 */
public class CheckPushMessageService extends Service {
    public static Context context;

    /** 控制检查的intent参数名 */
    public static final String INTENT_NAME_ACTION = "jumpCheck";
    /** 控制检查的intent参数值：跳过检查，重置闹钟服务 */
    public static final int ACTION_JUMPCHECK = 0;
    /** 控制检查的intent参数值：强制检查，重置闹钟服务 */
    public static final int ACTION_FORCECHECK = 1;
    /** 两次检查书签更新之间的：间隔时间 单位：ms  60 * 60 * 1000 */
    private static final long TIME_INTERVAL =60 * 60 * 1000;// 1小时

    private static final String TAG = "CheckPushMessageService";

    private String logTag = "CheckPushMessageService";

    private SharedPreferences sp;

    public List<CheckBookUpdateInfo> SMAndShuQiList;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    /** 查看是否需要检查更新并重设闹钟 */
    @Override
    public void onStart(final Intent intent, int startId) {
        sp = getSharedPreferences("pushId", MODE_PRIVATE);
        int action = ACTION_FORCECHECK;
        if (intent != null) {
            action = intent.getIntExtra(INTENT_NAME_ACTION, ACTION_FORCECHECK);
        }
        Log4an.e(logTag, "service start");
        // 0:00-6:00 不推送
        Date date = new Date();
        if (date.getHours() <= 5) {
            Log4an.e(logTag, "service return, for hours=" + date.getHours() + " or "
                    + ShuqiApplication.shuQiIsRunning());
            resetAlarm(this);
            stopSelf();
            return;
        }
        if(!isNeedCheck()){
            stopSelf();
            return;
        }
        
        if (ConfigVersion.hasNull()) {
            ConfigVersion.setTelInfos(this, Config.ROOT_PATH, Config.VERSION_INFO, Config.SOFT_ID,
                    Config.MIN_SDK_VERSION, 0, MyAccountManager.getInstance(this).getUserId(),
                    MyAccountManager.getInstance(this).getSession());
        }
        // 如果软件已开启，则1个小时后启动
        //!ShuqiApplication.shuQiIsRunning() &&
        if ( action == ACTION_FORCECHECK) {
            Log4an.e(logTag, "软件未开启，开始检查更新...");
            CheckPushMessageLinstener linstener = new CheckPushMessageLinstener() {
                @Override
                public void onFinish(int resultType, List<CheckPushMessageInfo> list) {
                    if (resultType == CheckPushMessage.TYPE_CHECKRESULT_HASACTION) {
                        CheckPushMessageInfo info = list.get(0);
                        String pushType = info.getBookId();
                        String title = info.getBookName();
                        String description = info.getUpdateTime();
                        String pushId = info.getSourceId();
                        String content = info.getMaxOid();
                        if (sp.getString("pushId", "0").equals(pushId)) {
                            // 已经接收过该消息后 就不再处理
                        } else 
                        {
                            Editor editor = sp.edit();
                            editor.putString("pushId", pushId);
                            editor.commit();
                            PendingIntent pt = null;
                            if ("2".equals(pushType)) {// 推送活动
                                
                                StatisticsUtils.onEvent(context,StatisticsEventID.PUSHMESSAGE_ACTION_NOTICE);
                                Log4an.e(logTag, "============推送新活动 web");
                                Intent intent =
                                        new Intent(Intent.ACTION_MAIN);
                                String pn = getPackageName();
                                ComponentName componentName =
                                        new ComponentName(pn, WebCommonActivity.class.getName());
                                intent.setComponent(componentName);
                                // 跳入webkit网页
                                if (!TextUtils.isEmpty(content)) {
                                    try {
                                        content = URLDecoder.decode(content, "utf-8");
                                        Log4an.i("youyang", "推送过来的url：" + content);
                                        if (!content.startsWith("http")) {
                                            content = "http://" + content;
                                        }
                                        Log4an.i("youyang", "rongcuohou推送过来的url：" + content);
                                        intent.putExtra(WebCommonActivity.INTENT_EXTRANAME_TITLE,
                                                title);
                                        intent.putExtra(WebCommonActivity.INTENT_EXTRANAME_URL,
                                                content);
                                        intent.putExtra("push_action", "open");
                                    } catch (UnsupportedEncodingException e) {
                                        e.printStackTrace();
                                    }
                                }
                                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                pt =
                                        PendingIntent.getActivity(CheckPushMessageService.this, 0,
                                                intent, PendingIntent.FLAG_UPDATE_CURRENT);
                            } else if ("1".equals(pushType)) {// 推送单本书籍
                                Log4an.e(logTag, "============推送单本书籍");
                                StatisticsUtils.onEvent(context,StatisticsEventID.PUSHMESSAGE_BOOK_NOTICE);
                                Intent intent =
                                        new Intent(getApplicationContext(), BookCoverActivity.class);
                                intent.putExtra(BookCoverActivity.INTENT_NAME_BOOKID, content);
                                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                String pn = getPackageName();
                                ComponentName componentName =
                                        new ComponentName(pn, BookCoverActivity.class.getName());
                                intent.setComponent(componentName);
                                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                intent.putExtra("push_book", "open");
                                pt =
                                        PendingIntent.getActivity(CheckPushMessageService.this, 0,
                                                intent, PendingIntent.FLAG_UPDATE_CURRENT);

                            } else if ("3".equals(pushType)) {
                            }
                            showNotify(title, description, pt, 0);
                        }

                    }
                    stopSelf();
                }
            };
            CheckPushMessage.checkActionAndSingleBook(getApplication(), MyAccountManager
                    .getInstance(context).getUserId(), linstener);
            resetAlarm(this);
        } else {
            resetAlarm(this);
            Log4an.e(logTag, "软件已经开启，不检查更新");
            stopSelf();
        }
        super.onStart(intent, startId);
    }

    @Override
    public void onDestroy() {
        Log4an.e(logTag, "service服务结束");
        super.onDestroy();
    }

    /**
     * 设置闹钟
     * 
     * @param nextStartTime 服务下次开启时候的时间
     * @param interval 两次的间隔开启时间
     */
    private static boolean resetAlarm(Context context) {
        Log4an.i("CheckPushMessageService", "reset alarm service");
        Intent intent = new Intent(context, CheckPushMessageService.class);
        PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
        // 取消旧闹钟
        try {
            alarmManager.cancel(pendingIntent);
        } catch (Exception e) {
            Log4an.d("CheckPushMessageService", "取消旧闹钟失败");
        }
        if (!FunctionsSwitch.isNotificationOpen(context)) {
            return false;
        }
        long currentTime = SystemClock.elapsedRealtime();
        long nextStartTime = currentTime + TIME_INTERVAL;
        alarmManager.set(AlarmManager.ELAPSED_REALTIME, nextStartTime, pendingIntent);
        // 类型、下次触发的时间，间隔时间、延迟意图
        Log4an.i("CheckPushMessageService", "reset service success 当前时间 " + currentTime + " 下次启动时间"
                + nextStartTime + " 大约 " + (TIME_INTERVAL / 1000) + " 秒之后启动");
        return true;
    }

    public static boolean startCheckPushMessageUpdate(Context content) {
        context = content;
        return resetAlarm(content);
    }

    /** 取消闹钟服务：检查更新并通知栏提醒功能 */
    public static boolean cancelCheckPushMessageUpdate(Context content) {
        Intent intent = new Intent(content, CheckPushMessageService.class);
        PendingIntent pendingIntent = PendingIntent.getService(content, 0, intent, 0);
        AlarmManager alarmManager = (AlarmManager) content.getSystemService(ALARM_SERVICE);
        // 取消旧闹钟
        try {
            alarmManager.cancel(pendingIntent);
            Log4an.d("CheckPushMessageService", "取消消息推送功能成功");
            return true;
        } catch (Exception e) {
            Log4an.d("CheckPushMessageService", "取消消息推送功能失败");
            return false;
        }
    }

    /** 显示通知栏提示内容 */
    private void showNotify(String title, String content, PendingIntent pt, int id) {
        // Notification管理器：设置一个唯一的ID，随便设置
        Notification notification =
                new Notification(R.drawable.icon, title, System.currentTimeMillis());
        notification.flags = Notification.FLAG_AUTO_CANCEL;
        // 后面的参数分别是显示在顶部通知栏的小图标，小图标旁的文字（短暂显示会自动消失）系统当前时间（不明白这个有什么用）
        notification.defaults = Notification.DEFAULT_SOUND;
        // 这是设置通知是否同时播放声音或振动，声音为Notification.DEFAULT_SOUND
        // 振动为Notification.DEFAULT_VIBRATE;
        // 全部为Notification.DEFAULT_ALL
        // 如果是振动或者全部，必须在AndroidManifest.xml加入振动权限
        // 点击通知后的动作，这里是转回main 这个Acticity
        notification.setLatestEventInfo(CheckPushMessageService.this, title, content, pt);
        ((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).notify(id, notification);
    }

    /** 关闭通知栏 */
    public static final void closeNotification(Context context) {
        ((NotificationManager) context.getSystemService(NOTIFICATION_SERVICE))
                .cancel(R.drawable.icon);
    }
    
    /***
     * 对比上次价差的时间当前是否需要检查更新
     * @return
     */
    public static boolean isNeedCheck(){
        long lastTime = SpConfig.getInstance().getLastUpdateBookMarkTime();
        long curTime = System.currentTimeMillis();
        long intervalTime = curTime - lastTime;
        boolean isNeed = intervalTime < 0 || intervalTime > TIME_INTERVAL;
        Log4an.e(TAG,(isNeed?"需要":"不需要")+"检查 push消息。 lastTime="+lastTime+" curTime="+curTime+" intervalTime="+(intervalTime/1000)+"秒");
        return isNeed;
    }
    
}
